package com.dhms.vostok1.repository

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.dhms.vostok1.data.fault.FaultListItemData
import com.dhms.vostok1.data.fault.FaultListQueryData
import com.dhms.vostok1.model.DeviceViewModel
import com.dhms.vostok1.service.net.NetworkApi
import com.dhms.vostok1.utils.toMap

class FaultListPagingSource(
    val api: NetworkApi,
    val faultSearchConditions: FaultListQueryData,
    val faultTotalCount: MutableLiveData<Int?>?
) : PagingSource<Int, FaultListItemData>() {
    override fun getRefreshKey(state: PagingState<Int, FaultListItemData>): Int? {
        //  * prevKey == null -> anchorPage is the first page.
        //  * nextKey == null -> anchorPage is the last page.
        //  * both prevKey and nextKey null -> anchorPage is the initial page, so
        //    just return null.
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, FaultListItemData> {
        val pos = params.key ?: 1
        var nextPageNumber: Int? = pos + 1
        try {
            val conditions = faultSearchConditions
            conditions.offset = pos
            val queryMap = conditions.toMap()!!
            val res = api.getFaultList(queryMap)
            val error = res.exceptionOrNull()
            if (error != null) {
                // 数据获取失败
                Log.e(DeviceViewModel.TAG, "error: $error")
                return LoadResult.Error(Throwable("获取告警列表数据失败", error))
            }
            val items = res.getOrNull()!!.body()!!.data!!.data
            faultTotalCount?.value =
                res.getOrNull()!!.body()?.data?.total ?: res.getOrNull()!!.body()?.data?.data?.size
            if (items.size < faultSearchConditions.limit) {
                nextPageNumber = null
            }
            return LoadResult.Page(
                data = items,
                if (pos <= 1) null else pos - 1,
                nextPageNumber
            )
        } catch (error: Throwable) {
            return LoadResult.Error(Throwable("获取告警列表数据失败", error))
        }
    }
}
